<script setup>
import { onMounted, ref } from 'vue';
import ButtonGroup from '../components/ButtonGroup.vue';
import { useAuthStore } from '@/stores/auth';
import {useRoute, useRouter} from 'vue-router'
import { queryPetsByPageAPI } from '@/apis/pet.js';
import { isAdopting } from '@/apis/adopt.js';
import { ElMessage, ElMessageBox } from 'element-plus';

const route = useRoute();
const router = useRouter();

/* ------按钮组及输入框------- */
const buttonList = [
  {
    key: 'paw',
    text: '全部宠物',
    icon: {
      active: '/icon/paw-sharp-blue.png',
      normal: '/icon/paw-sharp-black.png'
    }
  },
  {
    key: 'heart',
    text: '可领养',
    icon: {
      active: '/icon/heart-blue.png',
      normal: '/icon/heart-black.png'
    }
  },
  {
    key: 'home',
    text: '已领养',
    icon: {
      active: '/icon/home-blue.png',
      normal: '/icon/home-black.png'
    }
  },
  {
    key: 'man',
    text: '公',
    icon: {
      active: '/icon/man.png',
      normal: '/icon/man.png'
    }
  },
  {
    key: 'woman',
    text: '母',
    icon: {
      active: '/icon/woman.png',
      normal: '/icon/woman.png'
    }
  },
];

// 选中的按钮
const selectedBtn = ref('paw');

const handlerSelectBtn = (key) => {
  selectedBtn.value = key;
  queryPets();
}

// 输入框
const input = ref();

/* ------表格------- */
const tableData = ref([]);

const userStore = useAuthStore();

// 校验当前用户是否已领养过该宠物，且处于待审核状态
const isAdoptingPet = async (petId) => {
  await userStore.getUserDetail();
  const userId = userStore.userDetail.userId;
  const res = await isAdopting({userId: userId, petId: petId});
  if(res.data === true) {
    return true;
  }
  return false;
}

// 申请领养
const handleOperate = async (row) => {
  // 校验当前用户是否已领养过该宠物，且处于待审核状态
  const isAdopting = await isAdoptingPet(row.petId);
  if(isAdopting) {
    ElMessage.warning('您已领养过该宠物，正在审核中...');
    return;
  }

  router.push({
    path: '/adopt/apply-data', 
    query: { petId: row.petId }  // 用query传参（刷新页面不丢失）
  });
}

/* ------分页条------- */
const total = ref(0); // 总数据条数
const currentPage = ref(1); // 当前页码
const pageSize = ref(7); // 每页显示条数

// 构造请求参数（根据按钮、搜索框、分页状态）
const getQueryParams = () => {
  const params = {
    page: currentPage.value,
    pageSize: pageSize.value,
    name: input.value?.trim() || '' // 宠物名称（去空格）
  };

  // 根据选中的按钮，添加对应的筛选条件
  switch (selectedBtn.value) {
    case 'heart': // 可领养
      params.status = 'AVAILABLE'; 
      break;
    case 'home': // 已领养
      params.status = 'UNAVAILABLE';
      break;
    case 'man': // 公
      params.gender = 'MALE'; 
      break;
    case 'woman': // 母
      params.gender = 'FEMALE';
      break;
    default:
      break;
  }
  return params;
};

// 获取分页宠物信息
const queryPets = async () => {
  try {
    const params = getQueryParams();
    const res = await queryPetsByPageAPI(params);
    tableData.value = res.data.records;
    total.value = res.data.total; 
  } catch (err) {
    console.error('请求宠物列表失败：', err);
  }
};

// 每页条数变化时的回调
const handleSizeChange = (val) => {
  pageSize.value = val;
  queryPets();
};

// 当前页码变化时的回调
const handleCurrentChange = (val) => {
  currentPage.value = val;
  queryPets();
};

// 点击搜索图标触发查询
const handleSearch = () => {
  queryPets();
};
// 清除搜索框内容后触发查询
const handleClearInput = () => {
  queryPets();      
};

onMounted(() => queryPets());
</script>

<template>
    <div class="bar">
            <!-- 按钮组 -->
            <ButtonGroup
              :buttonList=buttonList
              :selectedBtn=selectedBtn
              @select="handlerSelectBtn"
            />

             <div class="search-input">
              <el-input
                v-model="input"
                @keyup.enter="handleSearch"
                @clear="handleClearInput"
                style="width: 452px; height: 42px;"
                placeholder="搜索宠物名称"
                clearable
              >
                <template #suffix>
                  <img @click="handleSearch" src="/icon/search.png" alt="搜索图标" width="18px" height="18px" style="cursor: pointer;">
                </template>
              </el-input>
             </div>

    </div>

    <div class="table">
            <el-table 
              :data="tableData" 
              style="width: 100%;"
              row-height="72"
              max-height="598px"
              :header-cell-style="{
                background: '#FAFAFA',
                color: '#404040',
                fontWeight: 'bold',
                height: '66px'
              }"
            >
              <el-table-column prop="name" align="center">
                <template #header>
                  <div class="table-header">
                    <img src="/icon/paw-sharp-black.png" alt="" width="18px" height="18px">
                    <span>名字</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="breedName" align="center">
                <template #header>
                  <div class="table-header">
                    <img src="/icon/variety.png" alt="" width="18px" height="18px">
                    <span>品种</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="center" width="250">
                <template #header>
                  <div class="table-header">
                    <img src="/icon/gender.png" alt="" width="18px" height="18px">
                    <span>性别</span>
                  </div>
                </template>
                <template #default="scope">
                  <div 
                    class="gender" 
                    :style="{ backgroundColor: scope.row.gender === 'MALE' ? '#2BAFF5' : '#F8469D' }">
                      <span>{{ scope.row.gender === 'MALE' ? '公' : '母' }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="status" align="center" width="250">
                <template #header>
                  <div class="table-header">
                    <img src="/icon/status.png" alt="" width="18px" height="18px">
                    <span>状态</span>
                  </div>
                </template>
                <template #default="scope">
                  <div 
                    class="status"
                    :style="{backgroundColor: scope.row.status === 'UNAVAILABLE' ? '#C5C3C3' : '#31C84B'}"
                  >
                    <span>{{ scope.row.status === 'UNAVAILABLE' ? '已领养' : '可领养'}}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="center">
                <template #header>
                  <div class="table-header">
                    <img src="/icon/operate.png" alt="" width="18px" height="18px">
                    <span>操作</span>
                  </div>
                </template>
                <template #default="scope">
                  <el-button 
                    type="text" 
                    class="operate-btn" 
                    :disabled = "scope.row.status === 'UNAVAILABLE'"
                    @click="handleOperate(scope.row)"  
                  >
                    <img 
                      :src="scope.row.status === 'UNAVAILABLE' ? '/icon/adopt-gray.png' : '/icon/adopt-blue.png'"
                      alt="操作" 
                      width="28px" 
                      height="28px"
                    >
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页条 -->
             <div class="pagination">
              <!-- 分页条 -->
                <!-- 
                  current-page：当前页码
                  page-size：每页显示条数
                  total：总数据条数
                  :page-sizes="[25]" ：每页显示条数的可选值（这里只保留25）
                  layout：分页组件布局
                  prev-text:上一页文本
                  next-text：下一页文本
                  @size-change：每页条数变化时触发
                  @current-change：当前页码变化时触发
                -->
                <el-pagination
                  v-model:current-page="currentPage"  
                  v-model:page-size="pageSize"        
                  :total="total"                     
                  layout="total, prev, pager, next, jumper, slot" 
                  @size-change="handleSizeChange"    
                  @current-change="handleCurrentChange"  
                >
                </el-pagination>
             </div>
    </div>
</template>

<style scoped>
.bar {
  display: flex;
  justify-content: space-between;
  margin-top: 12px;
  height: 60px;
}
.table-header {
  display: flex;        /* 开启 Flex 布局 */
  align-items: center;  /* 垂直居中） */
  justify-content: center; /* 水平居中 */
  gap: 6px;             /* 图标与文字的间距 */
  height: 100%;         /* 占满表头单元格的高度（66px） */
  font-size: 16px;
}
.gender {
  width: 41px;
  height: 26px;
  margin: 0 auto;
  padding: 4px 14px;
  line-height: 18px;
  color: #FFFFFF;
  border-radius: 5px;
}
.status {
  width: 59px;
  height: 26px;
  border-radius: 5px;
  color: #FFFFFF;
  font-size: 13px;
  text-align: center;
  margin: 0 auto;
  padding: 4px 10px;
  line-height: 18px;
}

/* 分页条 */
.pagination {
  position: absolute;
  right: 16px;
  margin-top: 10px;
  bottom: 20px;
}

:deep(.el-table) {
  --el-table-text-color: #2B2B2B;
  --el-table-border: none; 
}
/* 强制设置数据行（tr）的高度为72px */
:deep(.el-table .el-table__row) {
  height: 72px !important; 
}
</style>